package com.khd.problems_0801_0900;

/**
 * 875. 爱吃香蕉的珂珂
 *
 * @author kehandi
 * @title: Problem_0875_KokoEatingBananas
 * @projectName algorithm
 * @date 2025/5/20 07:17
 */
public class Problem_0875_KokoEatingBananas {

    public int minEatingSpeed(int[] piles, int h) {
        int l = 1;
        int r = 0;
        for (int pile : piles) {
            r = Math.max(r, pile);
        }

        // [l,r]不停二分
        int ans = 0;
        int m = 0;
        while (l <= r) {
            m = l + ((r - l) >> 1);
            if (f(piles, m) <= h) {
                // 达标，记录答案，去左侧二分
                ans = m;
                r = m - 1;
            } else {
                l = m + 1;
            }
        }
        return ans;
    }

    private long f(int[] piles, int speed) {
        long ans = 0;
        for (int pile : piles) {
            // pile / speed 的结果向上取整，如果都是
            ans += (pile + speed - 1) / speed;
        }
        return ans;
    }

    public static void main(String[] args) {
        // 测试
        int[] piles = {3, 6, 7, 11};
        int h = 8;
        Problem_0875_KokoEatingBananas kokoEatingBananas = new Problem_0875_KokoEatingBananas();
        System.out.println(kokoEatingBananas.minEatingSpeed(piles, h));
//        System.out.println(kokoEatingBananas.minEatingSpeed(new int[]{30, 11, 23, 4, 20}, 5));
//        System.out.println(kokoEatingBananas.minEatingSpeed(new int[]{30, 11, 23, 4, 20}, 6));

    }
}
